package com.itheima.servletlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

@WebServlet("/addStudentServlet")
public class addStudentservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过请求获取学生姓名
        String username = req.getParameter("username");
        //通过请求获取学生年龄
        String age = req.getParameter("age");
        //通过请求获取学生成绩
        String score = req.getParameter("score");
        //创建学生对象
        Student S = new Student();
        //设置学生姓名
        S.setUsername(username);
        //设置学生年龄
        S.setAge(Integer.parseInt(age));
        //设置学生成绩
        S.setScore(Integer.parseInt(score));

        //通过缓冲字符输出流在（F:\\GGBBSS.txt）文本写入数据
        BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\GGBBSS.txt", true));
        bw.write(S.getUsername() + "," + S.getAge() + "," + S.getScore());

        //新来换行
        bw.newLine();
        //释放流
        bw.close();
        //设置编码格式
        resp.setContentType("text/html;charset=UTF-8");
        //通过响应给客服端提示
        resp.getWriter().write("3秒后返回首页");
        //刷新响应消息并返回写入的URL文件
        resp.setHeader("Refresh", "3;URL=/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
